package com.dailyblue.java.spring.cloud.example.gateway.predicates;

import com.dailyblue.java.spring.cloud.example.gateway.config.AgeConfig;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
//自定义断言工厂，名称必须以RoutePredicateFactory结尾，名称必须以Age开头，Age是配置文件中上边红框上的Age
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeConfig> {

    public AgeRoutePredicateFactory() {
        super(AgeConfig.class);
    }
    // 依次设置AgeConfig参数和yml文件中的值对应
    public List<String> shortcutFieldOrder() {
        // 这里将配置文件中的值按照顺序赋值
        return Arrays.asList("minAge", "maxAge");
    }

    public Predicate<ServerWebExchange> apply(AgeConfig config) {
        int min = config.getMinAge();
        int max = config.getMaxAge();
        return exchange -> {
            // 获取到了请求参数age的值
            int age = Integer.parseInt(exchange.getRequest().getQueryParams().getFirst("age"));
            // 如果是true代表通过，否则条件失败
            return age >= min && age <= max;
        };
    }
}
